//
//  RHUserDetailVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/8/11.
//

#import "RHUserDetailVC.h"
#import "RHNavigationController.h"
#import "JXCategoryView.h"
#import "JXCategoryListContainerView.h"
#import "RHPlantListViewController.h"
#import "RHDeviceListViewController.h"
#import "RHDeviceDistributeVC.h"
#import "RHDeviceModel.h"
#import "RHEditUserInfoVC.h"

@interface RHUserDetailVC ()<JXCategoryListContainerViewDelegate,JXCategoryViewDelegate,JXCategoryTitleViewDataSource>
@property(nonatomic,strong)UIImageView *avatarImg;
@property(nonatomic,strong)QMUILabel *nameLab;
@property(nonatomic,strong)QMUILabel *emailLab;
@property(nonatomic,strong)QMUILabel *phoneLab;
@property(nonatomic,strong)QMUILabel *adressLab;

@property (nonatomic, strong) NSMutableArray *titles;

@property (nonatomic, strong) JXCategoryTitleView *categoryView;

@property (nonatomic, strong) JXCategoryListContainerView *listContainerView;

@property(nonatomic,strong)UIView *topView;


@end

@implementation RHUserDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    //解决内容往上偏移的问题
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.navigationItem.title = @"用户详情".rh_localized;
    self.view.backgroundColor = CFTabViewBgColor;
    self.titles = @[[NSString stringWithFormat:@"%@(0)",@"全部".rh_localized],
                    [NSString stringWithFormat:@"%@(0)",@"在线".rh_localized],
                    [NSString stringWithFormat:@"%@(0)",@"离线".rh_localized],
                    [NSString stringWithFormat:@"%@(0)",@"故障".rh_localized]].mutableCopy;
    //如果是安装工人,显示左边设备,右边电站
    if([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeSmallInstaller){
        self.titles = @[@"设备".rh_localized,@"电站".rh_localized].mutableCopy;
    }else{
        [self getStatusCount];
    }
    
    [self setupUI];
}

//在当前页面加入下面方法
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if([self.navigationController isKindOfClass:[RHNavigationController class]]){
        RHNavigationController *nav = (RHNavigationController*)self.navigationController;
        [nav setBackgoundClear:YES titleColor:nil];
    }

}
//如果仅设置当前页导航透明，需加入下面方法
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if([self.navigationController isKindOfClass:[RHNavigationController class]]){
        RHNavigationController *nav = (RHNavigationController*)self.navigationController;
        [nav setBackgoundClear:NO titleColor:nil];
    }

}

-(void)setupUI{
    
    [self addTopView];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getStatusCount) name:DeviceListNeedUpdateNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(modifyRemarkNameNO:) name:UserModifyRemarkName object:nil];
    kWeakSelf;
    //安装工人,终端,普通用户没有分发设备功能
    if([PrivateMange share].currentUser.hierarchyCode <= UserRoleTypeTerminalUser){
        UIButton *distributeBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0,40, 64)];
        [distributeBtn setImage:[UIImage imageNamed:@"device_distribute"] forState:UIControlStateNormal];
        [distributeBtn setBackgroundColor:UIColor.clearColor];
        [distributeBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
        [distributeBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
        [distributeBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc] initWithCustomView:distributeBtn];
        self.navigationItem.rightBarButtonItem = rightBarBtn;
        kWeakSelf;
        [[distributeBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            RHDeviceDistributeVC *vc = [[RHDeviceDistributeVC alloc] init];
            vc.userId = weakSelf.usermodel.userId;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }];
    }
    
    _listContainerView = [[JXCategoryListContainerView alloc] initWithType:JXCategoryListContainerType_ScrollView delegate:self];
    [self.view addSubview:self.listContainerView];
    
    _categoryView = [[JXCategoryTitleView alloc] initWithFrame:CGRectMake(0,0, [UIScreen mainScreen].bounds.size.width, 50)];
    self.categoryView.titles = self.titles;
    self.categoryView.backgroundColor = [UIColor whiteColor];
    self.categoryView.delegate = self;
//    self.categoryView.cellWidth = 60;
    self.categoryView.titleSelectedColor = kCOLOR_HEX(@"323233");
    self.categoryView.titleColor = kCOLOR_HEX(@"969799");
    self.categoryView.titleFont = [UIFont systemFontOfSize:14];
    self.categoryView.titleSelectedFont = [UIFont boldSystemFontOfSize:14];
    self.categoryView.titleColorGradientEnabled = YES;
    self.categoryView.titleLabelZoomEnabled = NO;
    self.categoryView.titleLabelZoomScale = 1.0;
    self.categoryView.cellSpacing = 30;
//    self.categoryView.contentEdgeInsetLeft = 20;
//    self.categoryView.contentEdgeInsetRight = 20;
    self.categoryView.titleLabelVerticalOffset = 0;
    [self.view addSubview:self.categoryView];
    self.categoryView.listContainer = self.listContainerView;
    
    if([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeSmallInstaller){
//        self.categoryView.contentEdgeInsetLeft = 50;
//        self.categoryView.contentEdgeInsetRight = 50;
    }
    
    JXCategoryIndicatorBackgroundView *backgroundView = [[JXCategoryIndicatorBackgroundView alloc] init];
     backgroundView.size = CGSizeMake(60, 3);
     backgroundView.indicatorColor = CMainColorGreen;
     backgroundView.indicatorHeight = 3;
//     backgroundView.indicatorWidth = 60;
     backgroundView.verticalMargin = -20;
     backgroundView.indicatorCornerRadius = 1.5;

     _categoryView.indicators = @[backgroundView];
  
    [_categoryView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(weakSelf.topView.mas_bottom).mas_offset(0);
        make.height.mas_equalTo(50);
    }];
    
    [_listContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(weakSelf.categoryView.mas_bottom).offset(0);
        make.bottom.mas_offset(0);
    }];
    
    
}

-(void)getStatusCount
{
    //安装工人显示设备和电站列表,以上级别显示设备列表
    if([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeSmallInstaller){
//        [self getUserPlantCount];
    }else{
        [self getUserDeviceCount];
    }
    
}


#pragma mark ---- 获取 下级用户 电站 状态数量
-(void)getUserPlantCount
{
    [BaseModel startGetWithCompletionAPIKey:H_userPlantStatus argument:@{@"userId":@(self.usermodel.userId)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            NSInteger allCount = [request.responseJSONObject[@"data"][@"all"] integerValue];
            NSInteger faultCount = [request.responseJSONObject[@"data"][@"fault"] integerValue];
            NSInteger offlineCount = [request.responseJSONObject[@"data"][@"offline"] integerValue];
            NSInteger onlineCount = [request.responseJSONObject[@"data"][@"online"] integerValue];
            NSArray *typeCountArr =  @[@(allCount),@(onlineCount),@(offlineCount),@(faultCount)];
            NSArray *titleArr = @[@"全部".rh_localized,@"在线".rh_localized,@"离线".rh_localized,@"故障".rh_localized];
            [self.titles removeAllObjects];
            for (int i = 0; i<titleArr.count; i++) {
                NSString *title = [NSString stringWithFormat:@"%@(%@)",titleArr[i],typeCountArr[i]];
                [self.titles addObject:title];
            }
            self.categoryView.titles = [self.titles copy];
            [self.categoryView reloadDataWithoutListContainer];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

#pragma mark ------ 获取 设备 各种状态数量
-(void)getUserDeviceCount
{
    [BaseModel startGetWithCompletionAPIKey:H_userDeviceStatus argument:@{@"userId":@(self.usermodel.userId)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            NSInteger allCount = [request.responseJSONObject[@"data"][@"all"] integerValue];
            NSInteger faultCount = [request.responseJSONObject[@"data"][@"fault"] integerValue];
            NSInteger offlineCount = [request.responseJSONObject[@"data"][@"offline"] integerValue];
            NSInteger onlineCount = [request.responseJSONObject[@"data"][@"online"] integerValue];
            NSArray *typeCountArr =  @[@(allCount),@(onlineCount),@(offlineCount),@(faultCount)];
            NSArray *titleArr = @[@"全部".rh_localized,@"在线".rh_localized,@"离线".rh_localized,@"故障".rh_localized];
            [self.titles removeAllObjects];
            for (int i = 0; i<titleArr.count; i++) {
                NSString *title = [NSString stringWithFormat:@"%@(%@)",titleArr[i],typeCountArr[i]];
                [self.titles addObject:title];
            }
            self.categoryView.titles = [self.titles copy];
            [self.categoryView reloadDataWithoutListContainer];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}



#pragma mark - JXCategoryViewDelegate

// 点击选中或者滚动选中都会调用该方法。适用于只关心选中事件，不关心具体是点击还是滚动选中的。
- (void)categoryView:(JXCategoryBaseView *)categoryView didSelectedItemAtIndex:(NSInteger)index {
    NSLog(@"%@", NSStringFromSelector(_cmd));
    // 侧滑手势处理
    self.navigationController.interactivePopGestureRecognizer.enabled = (index == 0);
    
}

// 滚动选中的情况才会调用该方法
- (void)categoryView:(JXCategoryBaseView *)categoryView didScrollSelectedItemAtIndex:(NSInteger)index {
    NSLog(@"%@", NSStringFromSelector(_cmd));
}

#pragma mark - JXCategoryListContainerViewDelegate
// 返回列表的数量
- (NSInteger)numberOfListsInlistContainerView:(JXCategoryListContainerView *)listContainerView {
    return  self.titles.count;
}

// 返回各个列表菜单下的实例，该实例需要遵守并实现 <JXCategoryListContentViewDelegate> 协议
- (id<JXCategoryListContentViewDelegate>)listContainerView:(JXCategoryListContainerView *)listContainerView initListForIndex:(NSInteger)index {
    //安装工人显示左边设备列表,右边电站列表,以上级别显示用户列表
    NSArray *typeArr = @[@(DevListTypeAll),@(DevListTypeOnline),@(DevListTypeOffline),@(DevListTypeFault)];
    //安装工人查看下级终端用户的电站和设备列表(不显示数量)
    if([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeSmallInstaller){
        if(index == 0){
            RHDeviceListViewController *vc = [[RHDeviceListViewController alloc]init];
            vc.userId = self.usermodel.userId;
            vc.canDelete = YES;
            vc.listType = (DevListType)[typeArr[index] integerValue];
            return vc;
        }else{
            RHPlantListViewController *vc = [[RHPlantListViewController alloc] init];
            vc.userId = self.usermodel.userId;
            vc.needAuth = YES;
            vc.index = index;
            return vc;
        }
       
    }else{
        
        RHDeviceListViewController *vc = [[RHDeviceListViewController alloc] init];
        //查下级用户,传userID
        vc.userId = self.usermodel.userId;
        vc.canDelete = YES;
        vc.index = index;
        vc.listType = (DevListType)[typeArr[index] integerValue];
        kWeakSelf;
        //刷新
        vc.refreshBlock = ^() {
            [weakSelf getUserDeviceCount];
        };
        return vc;

        
    }
    
}


-(void)addTopView
{
    
    UIImageView *bgImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, -self.navigationController.navigationBar.size.height-kSafe_top, kUI_WINDOW_W, kUI_WINDOW_W*454/750)];
    bgImg.image = [UIImage imageNamed:@"kwt_mine_bg"];
    [self.view addSubview:bgImg];
    
    
    UIView *topView  = kView;
    topView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:topView];
    self.topView = topView;
    
    UIImageView *avatarImg = [[UIImageView alloc]init];
    avatarImg.layer.cornerRadius = kScaleW(55)/2.0;
    avatarImg.layer.masksToBounds = YES;
    [avatarImg sd_setImageWithURL:[NSURL URLWithString:self.usermodel.avatar] placeholderImage:[UIImage imageNamed:@"kwt_avatar_default"]];
    [topView addSubview:avatarImg];
    self.avatarImg = avatarImg;
    
    //用户名
    QMUILabel *emailLab = [[QMUILabel alloc]init];
    emailLab.text = self.usermodel.remarkName?self.usermodel.remarkName:self.usermodel.userName;
    emailLab.textColor = kCOLOR_HEX(@"3F4443");
    emailLab.font = [UIFont systemFontOfSize:15];
    emailLab.textAlignment = NSTextAlignmentLeft;
    emailLab.numberOfLines = 2;
    [topView addSubview:emailLab];
    self.nameLab = emailLab;
    
    //邮箱
    QMUILabel *nickNameLab = [[QMUILabel alloc]init];
    nickNameLab.text = self.usermodel.email;
    nickNameLab.textColor = [UIColor colorWithHexString:@"3F4443" alpha:0.5];
    nickNameLab.font = [UIFont systemFontOfSize:11];
    nickNameLab.textAlignment = NSTextAlignmentLeft;
    [topView addSubview:nickNameLab];
    self.emailLab = nickNameLab;
    
    QMUILabel *phoneLab = [[QMUILabel alloc]init];
    phoneLab.text = self.usermodel.phonenumber;
    phoneLab.textColor = [UIColor colorWithHexString:@"3F4443" alpha:0.5];
    phoneLab.font = [UIFont systemFontOfSize:11];
    phoneLab.textAlignment = NSTextAlignmentLeft;
    [topView addSubview:phoneLab];
    self.phoneLab = phoneLab;
    
    QMUILabel *adressLab = [[QMUILabel alloc]init];
    adressLab.text = ValidNullDataToString(self.usermodel.address, @"--");
    adressLab.textColor = [UIColor colorWithHexString:@"3F4443" alpha:0.5];
    adressLab.font = [UIFont systemFontOfSize:11];
    adressLab.textAlignment = NSTextAlignmentLeft;
    [topView addSubview:adressLab];
    self.adressLab = adressLab;
    
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.offset(0);
    }];
    kWeakSelf;
    
    UIImageView *arrow = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"cell_arrow"]];
    [topView addSubview:arrow];
    [arrow mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(15);
        make.right.mas_offset(-15);
        make.centerY.equalTo(weakSelf.avatarImg);
    }];
    
    UIImageView *editImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"data_user_edit"]];
    [topView addSubview:editImg];
    [editImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(25);
        make.right.equalTo(arrow.mas_left).offset(-5);
        make.centerY.equalTo(weakSelf.avatarImg);
    }];
    
    QMUIButton *editBtn = [[QMUIButton alloc]init];
    [topView addSubview:editBtn];
    [editBtn addTarget:self action:@selector(editAction) forControlEvents:UIControlEventTouchUpInside];
    [editBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(editImg).offset(-15);
        make.right.equalTo(arrow).offset(15);
        make.height.offset(50);
        make.centerY.equalTo(editBtn);
    }];
    
    
    [_avatarImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.offset(15);
            make.width.height.offset(kScaleW(55));
    }];
    
    [_nameLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.avatarImg).offset(10);
            make.left.equalTo(weakSelf.avatarImg.mas_right).offset(10);
        make.right.equalTo(editImg.mas_left).offset(-3);
    }];
    
    [_emailLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(weakSelf.nameLab);
            make.top.equalTo(weakSelf.nameLab.mas_bottom).offset(5);
    }];
    
    [_phoneLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(weakSelf.nameLab);
            make.top.equalTo(weakSelf.emailLab.mas_bottom).offset(5);
    }];
    
    [_adressLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(weakSelf.nameLab);
            make.top.equalTo(weakSelf.phoneLab.mas_bottom).offset(5);
        make.bottom.mas_offset(-20);
    }];
}


-(void)editAction
{
    RHEditUserInfoVC *editVC = [[RHEditUserInfoVC alloc]init];
    editVC.usermodel = self.usermodel;
    [self.navigationController pushViewController:editVC animated:YES];
}


-(void)modifyRemarkNameNO:(NSNotification*)no
{
    if ([[no object]isKindOfClass:[RHUserModel class]]) {
        RHUserModel *userModel = [no object];
        self.nameLab.text = userModel.remarkName;
    }
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
